package com.seraph.zys.service.tree;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;


@Service
public class OrgTreeManagerImpl  extends JdbcDaoSupport implements OrgTreeManager{

	@Override
	public List getTreeNodeListByParentId(String parentId) {
		// TODO Auto-generated method stub
		String sql ="select a.org_code,a.org_name,a.report_lock_flag,b.leaf_sign from sc_org a ,sc_org_relation b where a.org_code=b.curr_org_code and a.fiscal_year="+getFiscalYear()+" and b.parent_org_code='"+parentId+"'";
		List list=getTreeNodeListBySql(sql);
		return list;
	}

	@Override
	public List getTreeNodeByOrgCode(String orgCode) {
		// TODO Auto-generated method stub
		String sql =null;
		List list=null;
		if(orgCode!=null && !"".equals(orgCode.trim())){
			sql="select a.org_code,a.org_name,a.report_lock_flag,b.leaf_sign from sc_org a ,sc_org_relation b where a.org_code=b.curr_org_code and a.fiscal_year="+getFiscalYear()+" and a.org_code='"+orgCode+"'";
			list=getTreeNodeListBySql(sql);
		}
		return list;
	}
	
	private List getTreeNodeListBySql(String sql){
//		Map map=getJdbcTemplate().queryForList(sql);
//		List<OrgTreeNode> list=new ArrayList<OrgTreeNode>(); 
//		if(map!=null && map.size()>0){
//			orgTreeNode=new OrgTreeNode();
//			orgTreeNode.setId((String)map.get("org_code"));
//			orgTreeNode.setText((String)map.get("org_name"));
//			if(map.get("report_lock_flag").toString().trim().equals("1")){
//				orgTreeNode.setChecked(true);
//			}
//			if(map.get("leaf_sign").toString().trim().equals("1")){
//				orgTreeNode.setLeaf(false);
//			}
//			list.add(orgTreeNode);
//		}
		List list=getJdbcTemplate().query(sql,new RowMapper(){
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException { 
				OrgTreeNode orgTreeNode=new OrgTreeNode();
				orgTreeNode.setId((String)rs.getString("org_code"));
				orgTreeNode.setText(rs.getString("org_name"));
				if(rs.getString("report_lock_flag").toString().trim().equals("1")){
					orgTreeNode.setChecked(true);
				}
				if(rs.getString("leaf_sign").toString().trim().equals("1")){
					orgTreeNode.setLeaf(false);
				}
				   return orgTreeNode; 
				}
		});
		return list;
	}
	
	private String getFiscalYear() {
		return String
		.valueOf(Calendar.getInstance().get(Calendar.YEAR) + 1);
	}

}
